package com.ruiyi.adrobot.web.controller.product;

import com.ruiyi.adrobot.beans.Picture;
import com.ruiyi.adrobot.beans.Product;
import com.ruiyi.adrobot.beans.common.ResultMsg;
import com.ruiyi.adrobot.dao.picture.PictureRepository;
import com.ruiyi.adrobot.dao.product.ProductRepository;
import com.ruiyi.adrobot.utils.ImageCompressUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;

/**
 * Created by tao.zeng on 2017/6/22.
 */
@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private PictureRepository pictureRepository;
    @Value("${staticPath}")
    private String staticPath;

    @RequestMapping(value = "/toAdd", method = RequestMethod.GET)
    public String toAdd() {
        return "product/add";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResultMsg add(Product product, @RequestParam(value = "picture", required = true) MultipartFile file) {
        try {
            // 判断文件是否为空
            String path = staticPath + "shop/" + product.getShopId();
            String fileName = System.currentTimeMillis() + ".png";
            if (!new File(path).exists()) {
                new File(path).mkdirs();
            }
            // 转存文件
            File newFile = new File(path + "/" + fileName);
            file.transferTo(newFile);
            ImageCompressUtil.saveMinPhoto(newFile.getPath(), newFile.getPath(), 50, 1);
            product.setCreateTime(new Date());
            Product product1 = productRepository.save(product);
            pictureRepository.save(new Picture(product1.getId(), "/shop/" + product.getShopId() + "/" + fileName, new Date()));
        } catch (Exception e) {
            return ResultMsg.error();
        }
        return ResultMsg.success(true);
    }
}
